<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>监管者仪表盘 - FinData管理系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #343a40;
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .sidebar .nav-link {
            font-weight: 500;
            color: #d9d9d9;
            padding: 0.75rem 1rem;
        }
        .sidebar .nav-link:hover {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.1);
        }
        .sidebar .nav-link.active {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.2);
        }
        .sidebar .nav-link i {
            margin-right: 10px;
        }
        .navbar {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        .navbar-brand {
            font-size: 1.5rem;
            font-weight: bold;
            color: #dc3545;
        }
        main {
            padding-top: 56px;
        }
        .content {
            padding: 20px;
        }
        .card {
            margin-bottom: 20px;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        .card-header {
            font-weight: bold;
        }
        .table th {
            background-color: #f8f9fa;
        }
        .error-message {
            color: #dc3545;
            margin-top: 10px;
            display: none;
        }
        .success-message {
            color: #28a745;
            margin-top: 10px;
            display: none;
        }
        
        /* 美化模态框样式 */
        .modal-content {
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }
        
        .modal-header {
            padding: 1.5rem;
            border-bottom: none;
        }
        
        .modal-body {
            padding: 1.5rem;
        }
        
        .modal-footer {
            padding: 1.5rem;
            border-top: none;
        }
        
        .modal-title {
            font-weight: 600;
        }
        
        /* 确认退出模态框样式 */
        #logoutConfirmModal .btn-danger {
            background-color: #dc3545;
            border-color: #dc3545;
            border-radius: 50px;
            padding: 8px 25px;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        #logoutConfirmModal .btn-danger:hover {
            background-color: #c82333;
            border-color: #bd2130;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(220, 53, 69, 0.3);
        }
        
        #logoutConfirmModal .btn-secondary {
            border-radius: 50px;
            padding: 8px 25px;
            font-weight: 500;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-md navbar-light bg-white fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">FinData</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarCollapse">
                <ul class="navbar-nav me-auto mb-2 mb-md-0">
                    <li class="nav-item">
                        <a class="nav-link active" href="#">监管者仪表盘</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <span class="navbar-text me-3">
                        <i class="bi bi-shield-lock"></i> <span id="supervisorUsername">监管者</span>
                    </span>
                    <button class="btn btn-outline-danger" id="logoutBtn">
                        <i class="bi bi-box-arrow-right"></i> 退出
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block sidebar collapse">
                <div class="sidebar-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="#" id="dashboardLink">
                                <i class="bi bi-speedometer2"></i> 仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" id="adminsLink">
                                <i class="bi bi-people"></i> 管理员管理
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主要内容区域 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="content">
                    <!-- 仪表盘内容 -->
                    <div id="dashboardContent">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                            <h1 class="h2">监管者仪表盘</h1>
                        </div>

                        <!-- 欢迎信息 -->
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">欢迎，监管者</h5>
                                <p class="card-text">您拥有系统的最高权限，可以管理所有管理员账户。</p>
                            </div>
                        </div>

                        <!-- 系统概览 -->
                        <div class="card mt-4">
                            <div class="card-header bg-danger text-white">
                                系统概览
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-4">
                                        <h5>管理员数量</h5>
                                        <h2 id="adminCount">0</h2>
                                    </div>
                                    <div class="col-md-4">
                                        <h5>最近登录</h5>
                                        <p id="lastLogin">无记录</p>
                                    </div>
                                    <div class="col-md-4">
                                        <h5>系统状态</h5>
                                        <span class="badge bg-success">正常运行</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 快速操作 -->
                        <div class="card mt-4">
                            <div class="card-header">
                                快速操作
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <button class="btn btn-primary w-100 mb-2" id="createAdminBtn">
                                            <i class="bi bi-person-plus"></i> 创建管理员
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 管理员管理内容 -->
                    <div id="adminsContent" style="display: none;">
                        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                            <h1 class="h2">管理员管理</h1>
                            <div class="btn-toolbar mb-2 mb-md-0">
                                <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#createAdminModal">
                                    <i class="bi bi-person-plus"></i> 添加管理员
                                </button>
                            </div>
                        </div>
                        
                        <div class="card">
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped table-hover">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>用户名</th>
                                                <th>创建时间</th>
                                                <th>最后登录</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody id="adminsTableBody">
                                            <!-- 管理员数据将通过JavaScript动态加载 -->
                                        </tbody>
                                    </table>
                                </div>
                                <div class="error-message mt-3" id="adminsErrorMessage"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 创建管理员模态框 -->
    <div class="modal fade" id="createAdminModal" tabindex="-1" aria-labelledby="createAdminModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createAdminModalLabel">创建管理员</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="createAdminForm">
                        <div class="mb-3">
                            <label for="newUsername" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="newUsername" required>
                        </div>
                        <div class="mb-3">
                            <label for="newPassword" class="form-label">密码</label>
                            <input type="password" class="form-control" id="newPassword" required>
                        </div>
                        <div class="error-message mt-3" id="createErrorMessage"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submitCreateAdmin">创建</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="confirmDeleteModal" tabindex="-1" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title" id="confirmDeleteModalLabel">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除管理员 "<span id="deleteAdminUsername"></span>" 吗？</p>
                    <p class="text-danger"><i class="bi bi-exclamation-triangle-fill"></i> 此操作不可撤销！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作结果模态框 -->
    <div class="modal fade" id="resultModal" tabindex="-1" aria-labelledby="resultModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="resultModalLabel">操作结果</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="resultModalBody">
                    操作已完成
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 退出确认模态框 -->
    <div class="modal fade" id="logoutConfirmModal" tabindex="-1" aria-labelledby="logoutConfirmModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title" id="logoutConfirmModalLabel">确认退出</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-question-circle-fill text-danger fs-1 me-3"></i>
                        <p class="mb-0">您确定要退出登录吗？</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmLogoutBtn">确认退出</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 显示结果消息
        function showResult(message, isSuccess = true) {
            const resultModal = document.getElementById('resultModal');
            const resultModalLabel = document.getElementById('resultModalLabel');
            const resultModalBody = document.getElementById('resultModalBody');
            
            if (isSuccess) {
                resultModalLabel.textContent = '操作成功';
                resultModalLabel.className = 'modal-title text-success';
                resultModalBody.innerHTML = `<div class="d-flex align-items-center">
                    <i class="bi bi-check-circle-fill text-success fs-1 me-3"></i>
                    <span>${message}</span>
                </div>`;
            } else {
                resultModalLabel.textContent = '操作失败';
                resultModalLabel.className = 'modal-title text-danger';
                resultModalBody.innerHTML = `<div class="d-flex align-items-center">
                    <i class="bi bi-x-circle-fill text-danger fs-1 me-3"></i>
                    <span>${message}</span>
                </div>`;
            }
            
            const modal = new bootstrap.Modal(resultModal);
            modal.show();
        }
        
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 获取监管者信息
            fetchSupervisorInfo();
            
            // 获取管理员数量
            fetchAdminCount();
            
            // 导航切换
            setupNavigation();
            
            // 创建管理员按钮事件
            document.getElementById('createAdminBtn').addEventListener('click', function() {
                const createAdminModal = new bootstrap.Modal(document.getElementById('createAdminModal'));
                createAdminModal.show();
            });
            
            // 提交创建管理员表单
            document.getElementById('submitCreateAdmin').addEventListener('click', createAdmin);
            
            // 确认删除按钮事件
            document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
                const adminId = this.getAttribute('data-admin-id');
                deleteAdmin(adminId);
                bootstrap.Modal.getInstance(document.getElementById('confirmDeleteModal')).hide();
            });
            
            // 退出登录
            document.getElementById('logoutBtn').addEventListener('click', function() {
                const logoutConfirmModal = new bootstrap.Modal(document.getElementById('logoutConfirmModal'));
                logoutConfirmModal.show();
            });
            
            // 确认退出登录
            document.getElementById('confirmLogoutBtn').addEventListener('click', function() {
                // 清除会话并跳转到登录页
                window.location.href = '/supervisor/login';
            });
        });
        
        // 获取监管者信息
        function fetchSupervisorInfo() {
            // 从会话中获取监管者信息
            const supervisorUsername = document.getElementById('supervisorUsername');
            // 这里应该从会话中获取，暂时使用固定值
            supervisorUsername.textContent = 'tjumis';
        }
        
        // 获取管理员数量
        function fetchAdminCount() {
            fetchAdmins().then(admins => {
                document.getElementById('adminCount').textContent = admins.length;
                
                if (admins.length > 0) {
                    const lastAdmin = admins.reduce((latest, admin) => {
                        if (!latest.lastLogin) return latest;
                        if (!admin.lastLogin) return latest;
                        return new Date(admin.lastLogin) > new Date(latest.lastLogin) ? admin : latest;
                    }, admins[0]);
                    
                    if (lastAdmin.lastLogin) {
                        document.getElementById('lastLogin').textContent = 
                            `${lastAdmin.username} (${new Date(lastAdmin.lastLogin).toLocaleString()})`;
                    }
                }
            });
        }
        
        // 设置导航切换
        function setupNavigation() {
            // 仪表盘
            document.getElementById('dashboardLink').addEventListener('click', function(e) {
                e.preventDefault();
                showContent('dashboardContent');
                setActiveLink(this);
            });
            
            // 管理员管理
            document.getElementById('adminsLink').addEventListener('click', function(e) {
                e.preventDefault();
                showContent('adminsContent');
                setActiveLink(this);
                // 加载管理员数据
                fetchAdmins().then(admins => {
                    displayAdmins(admins);
                });
            });
        }
        
        // 显示内容
        function showContent(contentId) {
            // 隐藏所有内容
            document.querySelectorAll('main > div > div[id$="Content"]').forEach(el => {
                el.style.display = 'none';
            });
            
            // 显示选中的内容
            document.getElementById(contentId).style.display = 'block';
        }
        
        // 设置活动链接
        function setActiveLink(link) {
            // 移除所有活动类
            document.querySelectorAll('.sidebar .nav-link').forEach(el => {
                el.classList.remove('active');
            });
            
            // 添加活动类到当前链接
            link.classList.add('active');
        }
        
        // 获取管理员列表
        async function fetchAdmins() {
            try {
                const response = await fetch('/api/supervisor/admins');
                
                if (response.ok) {
                    return await response.json();
                } else {
                    const errorMessage = document.getElementById('adminsErrorMessage');
                    const data = await response.json();
                    errorMessage.textContent = data.detail || '获取管理员列表失败';
                    errorMessage.style.display = 'block';
                    return [];
                }
            } catch (error) {
                console.error('获取管理员列表失败:', error);
                const errorMessage = document.getElementById('adminsErrorMessage');
                errorMessage.textContent = '获取管理员列表请求失败';
                errorMessage.style.display = 'block';
                return [];
            }
        }
        
        // 显示管理员列表
        function displayAdmins(admins) {
            const tableBody = document.getElementById('adminsTableBody');
            tableBody.innerHTML = '';
            
            if (admins.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="5" class="text-center">暂无管理员数据</td></tr>';
                return;
            }
            
            admins.forEach(admin => {
                const row = document.createElement('tr');
                
                // 格式化日期
                const createdAt = admin.createdAt ? new Date(admin.createdAt).toLocaleString() : '未知';
                const lastLogin = admin.lastLogin ? new Date(admin.lastLogin).toLocaleString() : '从未登录';
                
                row.innerHTML = `
                    <td>${admin.id}</td>
                    <td>${admin.username}</td>
                    <td>${createdAt}</td>
                    <td>${lastLogin}</td>
                    <td>
                        <button class="btn btn-sm btn-danger delete-admin" data-id="${admin.id}" data-username="${admin.username}">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                    </td>
                `;
                
                tableBody.appendChild(row);
            });
            
            // 添加删除事件监听
            document.querySelectorAll('.delete-admin').forEach(button => {
                button.addEventListener('click', function() {
                    const adminId = this.getAttribute('data-id');
                    const adminUsername = this.getAttribute('data-username');
                    
                    // 设置模态框内容并显示
                    document.getElementById('deleteAdminUsername').textContent = adminUsername;
                    document.getElementById('confirmDeleteBtn').setAttribute('data-admin-id', adminId);
                    
                    const confirmDeleteModal = new bootstrap.Modal(document.getElementById('confirmDeleteModal'));
                    confirmDeleteModal.show();
                });
            });
        }
        
        // 创建管理员
        async function createAdmin() {
            const username = document.getElementById('newUsername').value.trim();
            const password = document.getElementById('newPassword').value.trim();
            const errorMessage = document.getElementById('createErrorMessage');
            
            if (!username || !password) {
                errorMessage.textContent = '用户名和密码不能为空';
                errorMessage.style.display = 'block';
                return;
            }
            
            try {
                const response = await fetch('/api/supervisor/create-admin', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        username: username,
                        password: password
                    })
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('createAdminModal'));
                    modal.hide();
                    
                    // 清空表单
                    document.getElementById('newUsername').value = '';
                    document.getElementById('newPassword').value = '';
                    errorMessage.style.display = 'none';
                    
                    // 显示成功消息
                    showResult('管理员创建成功', true);
                    
                    // 刷新管理员列表
                    fetchAdmins().then(admins => {
                        displayAdmins(admins);
                        document.getElementById('adminCount').textContent = admins.length;
                    });
                } else {
                    errorMessage.textContent = data.detail || '创建管理员失败';
                    errorMessage.style.display = 'block';
                }
            } catch (error) {
                console.error('创建管理员请求失败:', error);
                errorMessage.textContent = '创建管理员请求失败，请稍后再试';
                errorMessage.style.display = 'block';
            }
        }
        
        // 删除管理员
        async function deleteAdmin(adminId) {
            try {
                const response = await fetch(`/api/supervisor/delete-admin/${adminId}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    // 显示成功消息
                    showResult('管理员删除成功', true);
                    
                    // 刷新管理员列表
                    fetchAdmins().then(admins => {
                        displayAdmins(admins);
                        document.getElementById('adminCount').textContent = admins.length;
                    });
                } else {
                    const data = await response.json();
                    const errorMessage = document.getElementById('adminsErrorMessage');
                    errorMessage.textContent = data.detail || '删除管理员失败';
                    errorMessage.style.display = 'block';
                    
                    // 显示失败消息
                    showResult(data.detail || '删除管理员失败', false);
                }
            } catch (error) {
                console.error('删除管理员请求失败:', error);
                const errorMessage = document.getElementById('adminsErrorMessage');
                errorMessage.textContent = '删除管理员请求失败，请稍后再试';
                errorMessage.style.display = 'block';
                
                // 显示失败消息
                showResult('删除管理员请求失败，请稍后再试', false);
            }
        }
    </script>
</body>
</html> 